/**
 * Created by WangMing on 15/12/9.
 */
define(["avalon",
		"text!./player_widget.html",
		"../../service",
		"../../utils/i18n",
		"expose?jwplayer!jwplayer"
], function(avalon, sourceHTML, api, i18n, jwplayer) {


		var widget = avalon.ui.playerWidget = function(element, data, vmodels) {




				var vmodel = avalon.define(data.playerWidgetId, function(vm) {

						vm.$player = avalon.mix({}, data.playerWidgetOptions);

						vm.$error = null;



						// var defaultPlayer = {
						// 		"title": "啊啊啊啊啊25",
						// 		"VideoResourcePath": {
						// 				"VideoShow": "/demo.mp4",
						// 				"HighDefinition": "/demo.mp4",
						// 				"IsRTMP": false,
						// 				"CaptionsFile": "/demo.srt"
						// 		},
						// 		"CreditVideoPath": "/demo.mp4", //CreateInstance.CreditsVideoDao.GetCreditVideoPath(this.ParentAlbum != null ? this.ParentAlbum.Guid : this.Video.Guid);
						// 		"videosmil": "/demo.smil",
						// 		"Spot": 12000,
						// 		"Video": {
						// 				"Name": "啊啊啊啊啊25",
						// 				"VideoSummary": "this is a video Summary of 啊啊啊啊啊25",
						// 				"Guid": "abcddfsfewfdsfsafdasfd",
						// 				"VideoCoverL": "/img1.jpg",
						// 				"VideoTimeInfoXML": "/Tools/JWPlayer/Service/VideoTimeInfoXML.aspx",
						// 				"VideoSWXML": "/Tools/JWPlayer/Service/VideoSWXML.aspx",
						// 		},

						// 		"guid": "abcddfsfewfdsfsafdasfd",

						// 		"ParentAlbum": null,
						// 		// "ParentAlbum" :{
						// 		//  "Guid": "abcdfe"
						// 		// },
						// 		"GetAlbumVideoInfoXML": "/Tools/Video/GetAlbumVideoInfoXML.aspx",
						// 		"playlist": "/Tools/Video/GetAlbumVideoPath.aspx?ParentAlbumGuid=",
						// 		"jwplayer": {
						// 				"flashplayer": "/Tools/JWPlayer7/jwplayer.flash.swf",
						// 				"skin": "/Tools/JWPlayer7/skins/glow.css",
						// 				"helpers": "/Tools/JWPlayer7/helpers",

						// 		},
						// 		"Notice": {
						// 				"Description": "Description Description Description",
						// 		}
						// };

						// avalon.mix(vm.$player,defaultPlayer);


						// post guid  album/video/online
						// get ajax-url  plugins-url 
						// error-handle 


						// @TODO authen
						var Global = {
								UserCode: "design",
								Site: "/"
						};


						vm.$init = function() {


							api.getItems({
								method: api.getVideoPlay,
					            query:{
					                id: vm.$player.Video.id
					            }
							},function(rec){
									if(!vm.$player.VideoResourcePath) vm.$player.VideoResourcePath = {};
			              			vm.$player.VideoResourcePath = _.merge(vm.$player.VideoResourcePath,rec.data)

							})


								element.innerHTML = sourceHTML;
								avalon.scan(element, [vmodel].concat(vmodels));


								// console.log($('.player-layout').width());

								var w = $('.player-layout').width() ? $('.player-layout').width() : 700,
										h = $('.player-wrapper').height() ? $('.player-wrapper').height() : 480;

								var device = (/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i.test(navigator.userAgent.toLowerCase()));


								if (device) {
										if ($('body').width() < 767) {
												w = $('body').width();
												h = w * 9 / 16;
										}

								}



								var MobileClient = function() {
												var sUserAgent = navigator.userAgent.toLowerCase();
												var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
												var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
												var bIsAndroid = sUserAgent.match(/android/i) == "android";
												if (bIsIpad || bIsIphoneOs || bIsAndroid) {
														return true;
												}
												return false;
										}
										//var isFlash = (navigator.userAgent.indexOf("iPad") == -1 && navigator.userAgent.indexOf("iPhone") == -1);

								var isFlash = !MobileClient();





								// handle url
								var nrURL = FormatHTML5Path(vm.$player.VideoResourcePath.VideoShow);
								var hdURL = FormatHTML5Path(vm.$player.VideoResourcePath.HighDefinition);


								if (MobileClient()) {
										nrURL = vm.$player.VideoResourcePath.VideoShow;
										hdURL = vm.$player.VideoResourcePath.HighDefinition;
								}



								if (vm.$player.VideoResourcePath.IsRTMP) {
										var appIndex = nrURL.lastIndexOf("//") + 1;
										nrURL = nrURL.slice(0, appIndex) + "mp4:" + nrURL.slice(appIndex + 1);
										if (hdURL != "") {
												hdURL = hdURL.slice(0, appIndex) + "mp4:" + hdURL.slice(appIndex + 1);
										} else {
												hdURL = nrURL;
										}
								}

								function changeVideo(pos, statue) {
										if (statue) {
												SwitchBitrate(hdURL);
										} else {
												SwitchBitrate(nrURL);
										}
								}

								var seekPoint = 0,
										finaleConfig;





								$(function() {
										seekPoint = parseInt(vm.$player.Spot / 1000);
										//console.log(" seek point: <%= this.VideoResourcePath.Seconds != 0? Math.Ceiling(this.VideoResourcePath.Seconds) : -1 %>");
										var autoJumpEnable = true;

										if (typeof(seekPoint) != "undefined" && seekPoint > 0) {
												autoJumpEnable = false;
										}

										var vid = vm.$player.Video.Guid;

										//  api.getUserViewHistory({guid:vm.$player.guid},function(result){



										//       //不然说明这么记录已经看完，-2为看完

										//       var seconds = result.Seconds || -1 ;

										//       if(seekPoint >0){
										//        MP4Player.appply(this,[vm.$player.guid,nrURL,seekPoint] );
										//      }else{


										//       finaleConfig = {
										//        jwplayerID: vm.$player.guid,
										//        videoGUID: vid,
										//        autoJump: autoJumpEnable,                     
										//        userID:Global.UserCode,
										//        authed: Global.UserCode!=null ? true : false,
										//        position: seconds, 
										//        lang: {
										//         lastTimePositionText:"上次观看到",
										//         moveonText: " 跳转继续观看 ",
										//         replayText: " 重新开始观看 "
										//       },
										//       onBeforeClose: function (pos,duration) {

										//         api.postUserViewHistory({pos:pos,duration:duration},function(res){});
										//       },
										//       onCompletePlay: function (duration) {

										//         api.postUserViewHistory({pos:-2,duration:duration},function(res){});

										//       }
										//     };
										//   }

										//   MP4Player.appply(this,[vm.$player.guid,nrURL,seconds] );



										// });

								});


								MP4Player.apply(this, [vm.$player.guid, nrURL]);

								function MP4Player(guid, url, seek) {
										$("#" + guid).show();

										var config = {
												// primary: isFlash ? 'flash': 'html5',
												primary: "html5",
												provider: "html5",
												// flashplayer:vm.$player.jwplayer.flashplayer,
												skin: {
														name: "glow",
														url: vm.$player.jwplayer.skin
												},
												image: vm.$player.Video.VideoCouverL,
												autostart: isFlash ? true : false,
												screencolor: '000000',
												wmode: 'transparent',
												height: h,
												width: w,
												plugins: {}

										}
										if (vm.$player.ParentAlbum == null) {
												if (vm.$player.VideoResourcePath.IsRTMP) {
														// rtmp

														if (!string.IsNullOrEmpty(this.VideoResourcePath.HighDefinition)) {

																config.file = FormatHTML5Path(Global.Site + vm.$player.videosmil);
														} else {

																config.file = url;
														}

												} else {
														// http
														if (vm.$player.VideoResourcePath.HighDefinition) {


																config.sources = [{
																		file: nrURL,
																		label: i18n.gettext("normal video pressed"),
																		"default": true
																}, {
																		file: hdURL,
																		label: i18n.gettext("loose video  pressed"),
																		"default": false
																}];

														} else {
																config.file = url;
														}

												}


										} else {

												config.playlist = vm.$player.playlist + vm.$player.ParentAlbum.Guid + "&VideoGuid=" + vm.$player.Video.Guid;
												config.repeat = 'list';

										}

										if (vm.$player.VideoResourcePath.IsRTMP) {
												config.rtmp = {
														bufferlength: 0.1
												};
										} else {
												config.startparam = "start";
										}

										if (vm.$player.ParentAlbum == null && vm.$player.VideoResourcePath.CaptionsFile) {
												//@TODO i18n
												// config.tracks = [{ file: "<%= this.VideoResourcePath.CaptionsFile %>", label: "Chinese" }];
										}

										// Plugins
										//   if(vm.$player.Video.VideoTimeInfoXML){
										//     config.plugins[vm.$player.jwplayer.helpers+"/cuehelper.js"] =  {
										//       dockname: i18n.gettext("cuehelper name"),
										//       title: i18n.gettext("class name Description :")+ vm.$player.Video.Name,
										//       introduction: vm.$player.Video.VideoSummary,
										//       repeatable: false,
										//     oncomplete: false,// 默认true
										//     lang: {
										//       noResultText: i18n.gettext("noResultText"),
										//       clickForReloopText: i18n.gettext("loop the clip")
										//     },
										//     list_item_height: 40,
										//     list_width: 380// make it short than 420 will display scrollbar;
										//   }


										//   if (vm.$player.ParentAlbum == null){

										//     config.plugins[vm.$player.jwplayer.helpers+"/cuehelper.js"].file = vm.$player.Video.VideoTimeInfoXML +"?Guid="+vm.$player.Video.Guid +"&TemplateGuid="+ Math.random();

										//   }else{ 
										//     config.plugins[vm.$player.jwplayer.helpers+"/cuehelper.js"].file =  vm.$player.GetAlbumVideoInfoXML+"?VideoInfoType=TimeInfoXML&ParentAlbumGuid="+vm.$player.ParentAlbum.Guid
										//     +"&VideoGuid="+  vm.$player.Video.Guid;

										//   } 

										// }

										// if(vm.$player.Video.VideoSWXML){
										//   config.plugins[vm.$player.jwplayer.helpers+"/cueswhelper.js"] =  {
										//     dockname: i18n.gettext("cueswhelper name"),
										//     title: i18n.gettext("class name description :")+ vm.$player.Video.Name,
										//     introduction: i18n.gettext("class summary :") +vm.$player.Video.VideoSummary,
										//     repeatable: false,
										//     oncomplete: false,// 默认true
										//     lang: {
										//       noResultText: i18n.gettext("noResultText"),
										//       clickForReloopText: i18n.gettext("loop the clip")
										//     },
										//     list_item_height: 40,
										//     list_width: 380
										//   }
										//   if (vm.$player.ParentAlbum == null){

										//     config.plugins[vm.$player.jwplayer.helpers+"/cueswhelper.js"].file = vm.$player.Video.SWXML +"?Guid=" + vm.$player.Video.Guid +"&TemplateGuid="+ Math.random();

										//   }else{ 
										//     config.plugins[vm.$player.jwplayer.helpers+"/cueswhelper.js"].file =  vm.$player.GetAlbumVideoInfoXML+"?VideoInfoType=SWXML&ParentAlbumGuid="+vm.$player.ParentAlbum.Guid 
										//     +"&VideoGuid="+  vm.$player.Video.Guid;

										//   } 
										// }
										// // 滚动消息【走马灯】
										// if (vm.$player.Notice != null){

										//  config.plugins[vm.$player.jwplayer.helpers+"/cueswhelper.js"] = {
										//   position: "top",
										//       text: vm.$player.Notice.Description,// filter HTML in back end.
										//       time: 5,
										//       font_size: 30,
										//       text_color: "FF7A66",
										//       backgroundcolor: "#000000"

										//     }
										//   }

										//  // 片头
										//  if (vm.$player.creditVideoPath  && vm.$player.Spot == 0){
										//   config.plugins[vm.$player.jwplayer.helpers+"/adhelper.js"] = {     

										//     adFront:vm.$player.creditVideoPath,
										//     enable: isFlash ? true :false,
										//     provider:isFlash ? "flash":"html5", 
										//     skipText:i18n.gettext(" jump the ad "),
										//     skipMessage: i18n.gettext(" wait for xx seconds"),
										//     barMessage: i18n.gettext(" loading ad ")
										//   }
										// }

										// if(vm.$player.Spot == 0){
										//   config.plugins[vm.$player.jwplayer.helpers+"/finalehelper.js"] = finaleConfig
										// }

										// console.log("jwplayer config", config);
										jwplayer(guid).setup(config);


										if (typeof seek != "undefined") {
												jwplayer(guid).onReady(function() {
														setTimeout(function() { jwplayer(guid).seek(seek); }, 500);
												});
										}

										// console.log("mp4Player",jwplayer(guid));


								} //mp4player function


								function FormatHTML5Path(url) {
										var temp1 = vm.$player.VideoResourcePath.RouteWebSite;
										var temp2 = vm.$player.VideoResourcePath.RouteRecourseSite;
										url = url.replace(temp1, temp2);
										return url;
								}




						}
						vm.$remove = function() {
								element.innerHtml = element.textContent = "";
						}

				})
				return vmodel;
		}
		return avalon;
})
